#!/usr/bin/env python
#coding=utf-8

from session import SessionBase
from  threading import currentThread
import uuid
from django.conf import settings
import thread, sys

DEFAULT_SESSION_ADDRESS = sys.platform == 'win32' and (('localhost', 8685,),) or r'/tmp/simple.session.django'
sessionName = settings.SESSION_COOKIE_NAME

TERMSIGS = None
if sys.platform != 'win32':
    from signal import signal, SIGQUIT, SIGINT, SIGTERM    
    TERMSIGS = (SIGQUIT, SIGINT, SIGTERM,)

baseSession = SessionBase(sessionName, DEFAULT_SESSION_ADDRESS, processMode=False, daemon=True)
baseSession.getSessionId = lambda : currentThread().sessionId

sessionConfig = baseSession.config
sessionStart = baseSession.start


class Session(object):
    TEST_COOKIE_NAME = 'testcookie'
    TEST_COOKIE_VALUE = 'worked'
    
    def __init__(self, base=baseSession):
        self._base = base
        
    def __contains__(self, key):
        return key in self._base
    
    def __getitem__(self, key):
        return self._base[key]
    
    def __setitem__(self, key, value):
        self._base[key] = value
    
    def __delitem__(self, key):
        del self._base[key]
        
    def lock(self, key):
        self._base.lock(key)
        
    def unlock(self, key):
        self._base.unlock(key)
        
    def pop(self, key, default=None):
        if default:
            if key not in self:
                return default
        r = self[key]
        del self[key]
        return r
    
    def setdefault(self, key, value):
        if key in self:
            return self[key]
        else:
            self[key] = value
            return value
        
    def set_test_cookie(self):
        self[self.TEST_COOKIE_NAME] = self.TEST_COOKIE_VALUE

    def test_cookie_worked(self):
        return self.get(self.TEST_COOKIE_NAME) == self.TEST_COOKIE_VALUE
    
    def delete_test_cookie(self):
        del self[self.TEST_COOKIE_NAME]
        
    def get(self, key, default=None):
        try:
            return self[key]
        except:
            return default
        
    def has_key(self, key):
        return key in self
    
    def cycle_key(self):
        pass
    
    def flush(self):
        self._logout = True

class Middleware(object):
    def __init__(self):
        settings = __import__('settings')
        if hasattr(settings, 'SESSION_SERVERS'):
            baseSession.config(settings.SESSION_SERVERS, startServer=False)
        baseSession.start()
    
    def process_request(self, request):
        request.session = Session()
        current = currentThread()
        if sessionName in request.COOKIES:
            sessionId = request.COOKIES[sessionName]
            current.sessionFlag = True
        else:
            sessionId = str(uuid.uuid4())
            current.sessionFlag = False
        current.sessionId = sessionId
        
    def process_response(self, request, response):
        current = currentThread()
        if not current.sessionFlag:
            response.set_cookie(sessionName, current.sessionId)
        current.sessionId = None
        session = request.session
        if hasattr(session, '_logout') and session._logout:
            response.delete_cookie(sessionName)
        return response

def terminate(sig, frame):
    print 'Received Signal:', sig
    import sys
    sys.exit()

try:
    for sig in TERMSIGS:
        signal(sig, terminate)
except:
    pass
